package com.oocl.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.oocl.dao.BookDao;
import com.oocl.pojo.Book;
import com.oocl.util.DBUtil;

public class BookDaoImpl implements BookDao{

	@Override
	public int addBook(Book b) {
		String sql = "insert into bookTable(uuid, bookname) values (?,?)";
		
		PreparedStatement pst =null;
		Connection con = null;
		int m = 0; 
		
		try {
			con = DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, b.getUid());
			pst.setString(2, b.getBookName());
			
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, null);
		}
		return m;
	}

	@Override
	public List<Book> findAllBook() {
		List<Book> list = new ArrayList<Book>();
		String sql = "select * from booktable";
		PreparedStatement pst = null;
		ResultSet rs = null;
		Connection con = DBUtil.createConnection();
		
		try {
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			
			while(rs.next()){
				Book b = new Book();
				b.setUid(rs.getString("uuid"));
				b.setBookName(rs.getString("bookname"));
				list.add(b);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, rs);
		}
		return list;
	}

	@Override
	public void initBook() {
		for(int i = 0; i < 5; i++){
			Book b = new Book(UUID.randomUUID().toString(), "book_" + i);
			addBook(b);
		}
	}
	public static void main(String[] args) {
		BookDaoImpl impl = new BookDaoImpl();
		impl.initBook();
	}

}
